package de.reichelt.fx;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.control.ComboBox;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import org.apache.commons.lang3.StringUtils;

/**
 * shows Listbox and selects value on key typing.
 * 
 * @author reicheltdi
 */
public class ComboBoxAddon {
  private String entry;

  public ComboBoxAddon(ComboBox cb) {
    cb.getEditor().setDisable(false);
    cb.getEditor().setEditable(true);
    cb.setOnKeyPressed(new EventHandler<KeyEvent>() {
      @Override
      public void handle(KeyEvent e) {
        cb.show();
        if (e.getText().length()==1 && StringUtils.isAsciiPrintable((e.getText()))) {
          entry += e.getText();
          cb.getSelectionModel().clearSelection();
          cb.getEditor().requestFocus();
          if (!entry.isEmpty()) {
            for (Object obj: cb.getItems()) {
              cb.getEditor().selectRange(0,entry.length());
              if (obj.toString().toLowerCase().startsWith(entry)) {
                cb.getSelectionModel().select(obj);
                break;
              }
            }
          }
        } else if (e.getCode().equals(KeyCode.BACK_SPACE)) {
          if (!entry.isEmpty()) entry = StringUtils.left(entry, entry.length()-1);
          cb.getSelectionModel().clearSelection();
          cb.getEditor().requestFocus();
          if (!entry.isEmpty()) {
            for (Object obj: cb.getItems()) {
              cb.getEditor().selectRange(0,entry.length());
              if (obj.toString().toLowerCase().startsWith(entry)) {
                cb.getSelectionModel().select(obj);
                break;
              }
            }
          }
        }
      }
    });
    cb.showingProperty().addListener(new ChangeListener<Boolean>() {
      @Override
      public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
        entry = "";
      }
    });
  }
  
  
}
